package org.pictual.controller.mainPackage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.pictual.controller.Controlador;
import org.pictual.controller.MyImage;

public class MainServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4414860983355481240L;

	protected static Logger log= Logger.getLogger(MainServlet.class);
	
	private static final int MAX_IMAG = 6;
	private static final int MAX_LANGS = 4;
	private static String USER_AGENT="";
	private WikiDicParser[] _wikiDicParsers;
	//private WikiDicTransParser[] _wikiDicTransParser;
	private WikiDicParser _currentDicParser;
	Vector<String> defsVector=new Vector<String>();
	Vector<String> examsVector=new Vector<String>();
	Vector<String> myOut=new Vector<String>();
	String pronunciation;
	String gender;
	String plural;
	String URL;
	Boolean verb;
	Vector<String> audio=new Vector<String>();
	String[] langz={"en", "es", "de", "fr"};

	private Controlador controlador;

	@Override
	public void init() throws ServletException {
		super.init();
		_wikiDicParsers = new WikiDicParser[MAX_LANGS];
		_wikiDicParsers[0] = new EnglishWikiDicParser();
		_wikiDicParsers[1] = new SpanishWikiDicParser();
		_wikiDicParsers[2] = new GermanWikiDicParser();
		_wikiDicParsers[3] = new FrenchWikiDicParser();

		//_wikiDicTransParser = new WikiDicTransParser[MAX_LANGS];
		//_wikiDicParsers[0] = new EnglishWikiDicTransParser();
		//_wikiDicParsers[0] = new SpanishWikiDicParser();
	}

	private BufferedReader getStreamForWeb(String addr) {
		try {
			System.out.println(addr);
			URL url = new URL(addr);
			HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();

			httpcon.addRequestProperty("User-Agent", USER_AGENT);
			//            httpcon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-EN; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10");
			httpcon.setDoInput(true);
			InputStream inStream = httpcon.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
			return reader;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}



//	void findImages(String query, ParamWrapper wrapper) {
		// input = getStreamForWeb("http://images.google.com/images?q=" + query.replace(' ', '_'));
		//unfilter
		//BufferedReader input = getStreamForWeb("http://images.google.com/images?um=1&hl=en&safe=off&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&tbs=isch%3A1&sa=1&q=" + query.replace(' ', '_')+"&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=&start=0");
		//moder8
		//BufferedReader input = getStreamForWeb("http://images.google.com/images?um=1&hl=en&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&tbs=isch%3A1&sa=1&q=" + query.replace(' ', '_')+" &btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=&start=0");
		//strict filter
		//BufferedReader input = getStreamForWeb("http://images.google.com/images?um=1&hl=en&safe=active&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&tbs=isch%3A1&sa=1&q=" + query.replace(' ', '_')+"&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=&start=0");

		//commercial use, mx, try this,,
//		System.out.println("Query: "+query);
//		System.out.println("Query tratada: "+removeSpacesForImages(query));
		//        BufferedReader input = getStreamForWeb("http://www.google.es/images?as_q="+removeSpacesForImages(query)+"&safe=on");
		//        System.out.println("GOOGLE_IMAGE:"+input.toString());


//		Vector<MyImage> images = GoogleSearchImg.queryForImages(removeSpacesForImages(query));
		//TODO guardar imagenes en base de datos
//		wrapper.setImages(images);
//	}

	protected String translate(String query, int lan1, int lan2) {
		if (lan1 == lan2) {
			return query;
		} else {
			BufferedReader reader = getStreamForWeb(Language.Wiki(lan1) + query.replace(' ', '_'));
			WikiParser wikiParser = new WikiParser(reader);
			return wikiParser.Parse(lan2).toLowerCase();
		}
	}

//	protected int findInformation(String query2, String query, ParamWrapper wrapper,int lang1, int lang2) throws Exception{
//		int option = 0;
//		if(!query2.contains(" ")){
//			query2 = query;
//		}
//		query2 = removeSpacesForInformation(query2);
//		query2 = cambiar(query2);
//
//		String origen = langz[lang1];
//		String destino = langz[lang2];
//		System.out.println("findInformation for: "+query2+" with language "+origen +" "+destino);
//		
//		controlador = new Controlador(query2, origen, destino);
//		int datos=controlador.checkDataSource();
		

		/////////
		
//		session.setAttribute("myOut", defsVector);
//		session.setAttribute("myOutEx", examsVector);
//		session.setAttribute("myOutPron", pronunciation);
//		session.setAttribute("myOutAudio", audio);
//		session.setAttribute("myOutGender", gender);
//		session.setAttribute("myOutPlural", plural);
//		session.setAttribute("verb", verb);
//		session.setAttribute("url", URL);
//		System.out.println("----------------------------------------------------");
//		System.out.println("query:"+query);
//		System.out.println("----------------------------------------------------");
//		request.setAttribute("info", wrapper);
//		RequestDispatcher disp = request.getRequestDispatcher(request.getParameter("ref"));
//		disp.forward(request, response);
		
		
		//TODO pasar VO a vista
//		defsVector.add(controlador.getDefinicionVO().getDefinicion_1());
//		defsVector.add(controlador.getDefinicionVO().getDefinicion_2());
//		defsVector.add(controlador.getDefinicionVO().getDefinicion_3());
//		examsVector.add(controlador.getDefinicionVO().getEjemplo_1());
//		examsVector.add(controlador.getDefinicionVO().getEjemplo_2());
//		examsVector.add(controlador.getDefinicionVO().getEjemplo_3());
//		audio.add(controlador.getIdiomaVO().getAudio());
//		gender=controlador.getIdiomaVO().getGenero();
//		plural=controlador.getIdiomaVO().getPlural();
//		pronunciation=controlador.getIdiomaVO().getPronunciacion();
		/////////
		
//		return datos;


//	}
//	        String url="http://"+langz[lang2]+".wiktionary.org/wiki/"+query2+"?action=render";
	//        System.out.println("LANGUAGE.url=  "+url);
//	        BufferedReader reader1 = getStreamForWeb(url);
	//        URL = url;
	//        if(lang1 != lang2){
	//            WikiDicParser parser = _wikiDicParsers[lang2];
	//            parser.query=query;
	//            if(!parser.Parse(reader1,lang1) && langz[lang1].equals("de")){	//Si el parse es false y el lenguage 1 es aleman
	//                option++;
	//                query2 = query.toLowerCase();
	//                url="http://"+langz[lang2]+".wiktionary.org/wiki/"+query2+"?action=render";
	//                System.out.println("LANGUAGE.url=  "+url);
	//                reader1 = getStreamForWeb(url);
	////              if(lang1 != lang2){
	//                parser = _wikiDicParsers[lang2];
	//                parser.query=query;
	//                if(!parser.Parse(reader1,lang1)){
	//                    option++;
	//                    query2 = query2.toUpperCase().charAt(0) + query2.substring(1);
	//                    url="http://"+langz[lang2]+".wiktionary.org/wiki/"+query2+"?action=render";
	//                    System.out.println("LANGUAGE.url=  "+url);
	//                    reader1 = getStreamForWeb(url);
	////                  if(lang1 != lang2){
	//                    parser = _wikiDicParsers[lang2];
	//                    parser.query=query;
	//                    if(!parser.Parse(reader1,lang1)){
	//                        option++;
	//                    }
	//                }
	//            }
	//            defsVector.clear();
	//            defsVector=parser.getDefList().getDefinitions();
	//            examsVector.clear();
	//            examsVector=parser.getDefList().getExamples();
	//            pronunciation = parser.getDefList().getPronunciation();
	//            gender = parser.getDefList().getGender();
	//            plural = parser.getDefList().getPlural();
	//            audio = parser.getDefList().getAudios();
	//            verb = parser.getDefList().getVerb();
	//            System.out.println("----------------------------------------------");
	//            System.out.println("Printing_DefsVector");
	//            for(int i=0;i<defsVector.size();i++){
	//            	if (defsVector.get(i).equals("<li></li>"))
	//            		defsVector.remove(i);
	//            	else
	//               System.out.println(defsVector.get(i) );
	//            }
	//            System.out.println("Printing_ExamsVector");
	//            for(int i=0;i<examsVector.size();i++){
	//               System.out.println(examsVector.get(i) );
	//            }
	//            System.out.println("Printing_Pronunciation");
	//            System.out.println(pronunciation);
	//            System.out.println("Printing_Audio");
	//            for(int i=0;i<audio.size();i++){
	//               System.out.println(audio.get(i) );
	//            }
	//            System.out.println("Printing_Gender");
	//            System.out.println(gender);
	//            System.out.println("Printing_Plural");
	//            System.out.println(plural);
	//            query = cambiar(query);
	//            System.out.println("Find_Info:"+query);
	//            if (defsVector.size()<2){
	//            	System.out.println("No results");
	//            	defsVector.add("No results found for: " + query);
	//            }
	//            if(examsVector.size() < 1){
	//                examsVector.add("No examples found for: " +query);
	//            }
	//            System.out.println("----------------------------------------------");
	//CategoriesWrapper categories = _currentDicParser.GetCategoriesWrapper();
	//Vector<String> otherLanguages = _currentDicParser.GetOtherLanguages();
	//}
	/*
        String queryTranslated = translate(query, lang1, lang2);
        BufferedReader reader = getStreamForWeb(Language.WikiDik(lang2) + query.replace(' ', '_'));
        _currentDicParser = _wikiDicParsers[lang2];
        _currentDicParser.Parse(reader);

        CategoriesWrapper categories = _currentDicParser.GetCategoriesWrapper();
        Vector<String> otherLanguages = _currentDicParser.GetOtherLanguages();

        if (!categories.isEmpty()) {
            wrapper.setInformation(categories);
            wrapper.setState(ParamWrapper.WrapperState.DEFINITION);
        } else if (!otherLanguages.isEmpty()) {
            wrapper.setOtherLanguages(otherLanguages);
            wrapper.setState(ParamWrapper.WrapperState.OTHER_LANGS);
        }

        setTitle(wrapper, query,queryTranslated);*/
	//            return option;
	//    }




	/** Trims blank spaces from an input string.
	 */
	public String removeSpacesForInformation(String s){
		return s.replaceAll(" ", "_");   //trimmedString;
	}

	public String removeSpacesForImages(String s){
		s = cambiar(s);
		return s.replaceAll(" ","+");   //trimmedString;
	}


	protected void setTitle(ParamWrapper wrapper, String query, String queryTranslated) {
		if (wrapper.getState() == ParamWrapper.WrapperState.DEFINITION) {
			if (query.equals(queryTranslated)) {
				wrapper.setTitle(query + " definitions:");
			} else {
				wrapper.setTitle(query + "  -  " + queryTranslated);
			}
		} else if (wrapper.getState() == ParamWrapper.WrapperState.OTHER_LANGS) {
			wrapper.setTitle(query + " found for these languages:");
		} else {
			wrapper.setTitle("No results found for: " + query);
		}
	}

	public String cambiar(String query2){
		query2 = query2.replaceAll("%C3%83%C2%A1", "Ã¡");
		query2 = query2.replaceAll("%C3%83%C2%A9", "Ã©");
		query2 = query2.replaceAll("%C3%83%C2%AD", "Ã­");
		query2 = query2.replaceAll("%C3%83%C2%B3", "Ã³");
		query2 = query2.replaceAll("%C3%83%C2%BA", "Ãº");
		query2 = query2.replaceAll("%C3%83%C2%B1", "Ã±");
		query2 = query2.replaceAll("%C3%83%C2%BC", "Ã¼");
		query2 = query2.replaceAll("%C3%83%C2%AB","Ã«");
		query2 = query2.replaceAll("%C3%83%C2%AF", "Ã¯");
		query2 = query2.replaceAll("%C3%83%C2%B6", "Ã¶");
		query2 = query2.replaceAll("%C3%83%C2%A4", "Ã¤");
		query2 = query2.replaceAll("%C2%81%C2%A2", "ï�¢");
		query2 = query2.replaceAll("%C3%83%C2%A2", "Ã¢");
		query2 = query2.replaceAll("%C3%83%C2%AA", "Ãª");
		query2 = query2.replaceAll("%C3%83%C2%AE", "Ã®");
		query2 = query2.replaceAll("%C3%83%C2%B4", "Ã´");
		query2 = query2.replaceAll("%C3%83%C2%BB", "Ã»");
		query2 = query2.replaceAll("%C3%83%C2%A0", "Ã ");
		query2 = query2.replaceAll("%C3%83%C2%A8", "Ã¨");
		query2 = query2.replaceAll("%C3%83%C2%AC", "Ã¬");
		query2 = query2.replaceAll("%C3%83%C2%B2", "Ã²");
		query2 = query2.replaceAll("%C3%83%C2%B9", "Ã¹");
		query2 = query2.replaceAll("%C3%83%C2%BF", "Ã¿");
		query2 = query2.replaceAll("%C3%83%C2%81", "Ã�");
		query2 = query2.replaceAll("%C3%83%C2%89", "Ã‰");
		query2 = query2.replaceAll("%C3%83%C2%8D", "Ã�");
		query2 = query2.replaceAll("%C3%83%C2%93", "Ã“");
		query2 = query2.replaceAll("%C3%83%C2%9A", "Ãš");
		query2 = query2.replaceAll("%C3%83%C2%80", "Ã€");
		query2 = query2.replaceAll("%C3%83%C2%88", "Ã‰");
		query2 = query2.replaceAll("%C3%83%C2%8C", "Ã�");
		query2 = query2.replaceAll("%C3%83%C2%92", "Ã“");
		query2 = query2.replaceAll("%C3%83%C2%99", "Ãš");
		query2 = query2.replaceAll("%C3%83%C2%84", "Ã„");
		query2 = query2.replaceAll("%C3%83%C2%8B", "Ã‹");
		query2 = query2.replaceAll("%C3%83%C2%8F", "Ã�");
		query2 = query2.replaceAll("%C3%83%C2%96", "Ã–");
		query2 = query2.replaceAll("%C3%83%C2%9C", "Ãœ");
		query2 = query2.replaceAll("%C3%85%C2%93", "Å“");
		query2 = query2.replaceAll("%C3%83%C2%A7", "Ã§");
		query2 = query2.replaceAll("%C3%83%C2%9F", "ÃŸ");
		return query2;
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		//session.setAttribute("langLeft", "en");
		//session.setAttribute("langRight", "en");
		USER_AGENT=request.getHeader("user-agent");
		System.out.println("User-agent: "+USER_AGENT);
		String query2 = request.getParameter("query");
		System.out.print("try:"+query2);
		String query = URLEncoder.encode(request.getParameter("query"), "UTF-8");
		/* String langLeft = (String)session.getAttribute("langLeft");
        String langRight = (String)session.getAttribute("langRight");*/

		String langLeft = request.getParameter("from");
		String langRight = request.getParameter("to");
		if  ( (langLeft.equals("")) || ((langLeft.equals(null)))  )
			langLeft="en";
		if (langRight.equals("") || ((langRight.equals(null)))  )
			langRight="en";


		System.out.println("Session_Langs:"+langLeft+"_"+langRight);

		session.setAttribute("left", langLeft);
		session.setAttribute("rigth", langRight);
		int lang1 = Language.resolve(langLeft);
		int lang2 = Language.resolve(langRight);
		System.out.print("<<<<<<<<<<<<<<<:langLeft:"+langLeft);
		System.out.println(":::langRight:"+langRight+">>>>>>>>>>>>>>>>>>>>>>>");
		session.setAttribute("query", query);
		ParamWrapper wrapper = new ParamWrapper();
//		findImages(query, wrapper);
		//TODO pasar el wrapper
//		int option = 0;
		try{
//			option = findInformation(query2, query, wrapper,lang1,lang2);
			if(!query2.contains(" ")){
				query2 = query;
			}
			query2 = removeSpacesForInformation(query2);
			query2 = cambiar(query2);

			String origen = langz[lang1];
			String destino = langz[lang2];
			System.out.println("findInformation for: "+query2+" with language "+origen +" "+destino);
			String ruta = getServletContext().getRealPath("/");
			ruta = ruta.substring(0, ruta.indexOf("."))+"Pictual/";
			System.out.println("RUTA: "+ruta);
			controlador = new Controlador(query2, origen, destino, ruta);
			int datos=controlador.checkDataSource();
			Vector<MyImage> images=controlador.findImages(datos);
			wrapper.setImages(images);
			
			if(datos==0)controlador.insertInDataBase();
			
		} catch(Exception e){
			log.error("Error: ", e);
		}

//		if(!query2.contains(" ")){
//			query2 = query;
//		}
//		query2 = removeSpacesForInformation(query2);
//		query2 = cambiar(query2);
//
//		query = cambiar(query);
//		session.setAttribute("query", query);
		//        switch(option){
		//            case 1:
		//                session.setAttribute("query", query.toLowerCase());
		//                break;
		//            case 2:
		//                session.setAttribute("query", query.toUpperCase().charAt(0)+query.toLowerCase().substring(1));
		//                break;
		//        }
		System.out.println(defsVector.add(controlador.getDefinicionVO().getDefinicion_1()));
		System.out.println(defsVector.add(controlador.getDefinicionVO().getDefinicion_2()));
		System.out.println(defsVector.add(controlador.getDefinicionVO().getDefinicion_3()));
		
		if(query2.contains(" ") || query2.contains("ÃƒÂŸ")){
			session.setAttribute("query", query2.replace("ÃƒÂŸ", "ÃŸ"));
		}
		session.setAttribute("myOut", defsVector);
		session.setAttribute("myOutEx", examsVector);
		session.setAttribute("myOutPron", pronunciation);
		session.setAttribute("myOutAudio", audio);
		session.setAttribute("myOutGender", gender);
		session.setAttribute("myOutPlural", plural);
		session.setAttribute("verb", verb);
		session.setAttribute("url", URL);
		System.out.println("----------------------------------------------------");
		System.out.println("query:"+query);
		System.out.println("----------------------------------------------------");
		request.setAttribute("info", wrapper);
		RequestDispatcher disp = request.getRequestDispatcher(request.getParameter("ref"));
		disp.forward(request, response);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}
}

